﻿using Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PublicMethod;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace OrderingOnlineWeChat.Controllers
{
    public class InformationController : BaseControl
    {
        //
        // GET: /Information/
        #region 声明
        ZHHQService.Service1Client server1 = new ZHHQService.Service1Client();
        DCXTService.Service1Client server2 = new DCXTService.Service1Client();
        #endregion

        #region View
        //首页
        public ActionResult Index()
        {
            return View();
        }
        //地址管理页
        public ActionResult Address()
        {            
            return View();
        }
        //新增地址页
        public ActionResult AddAddress()
        {
            return View();
        }
        public ActionResult AddAddressV()
        {
            return View();
        }
        //我的钱包页
        public ActionResult MyWalt()
        {
            return View();
        }
        //我的积分页
        public ActionResult Integral()
        {
            return View();
        }
        public ActionResult SelectAdd()
        {
            return View();
        }
        //商城信息列表
        public ActionResult ListInformation()
        {
            return View();
        }
        //商城信息详情
        public ActionResult DetailsInformation()
        {
            return View();
        }
        #endregion

        //获取session
        public string GetSession()
        {
            string userJson = JsonConvert.SerializeObject(Session[SessionStorage.OpenID]);
            return userJson;
        }

        #region 获取所有送餐范围        
        public ActionResult getrange()
        {
            try
            {
                Model.View_User userinfoModel = (Model.View_User)Session[SessionStorage.UserLogin];//将Session保存的实体转成可直接使用的实体
                int acc = int.Parse(userinfoModel.AccID.ToString());
                string result = server2.GetAllMerSendAdd(1, 1000, GetYZM._YZM, 1);
                Model.DataResult dr = ParseClass<Model.DataResult>.StrDeserialize(result, 1);
                List<Model.Order_MerSendAdd_T> ls = new List<Model.Order_MerSendAdd_T>();
                JObject jb = JObject.Parse(result);
                IList<JToken> jieguo = jb["rows"].Children().ToList();
                ls = ParseClass<Model.Order_MerSendAdd_T>.JsonList(jieguo);
                var data = new
                {
                    total = ls.Count,
                    rows = ls
                };
                return Json(data);
            }
            catch (Exception) { return null; }
        }
        #endregion

        //新的送餐范围接口
        public ActionResult GetSendAddFromMerId(string merid)
        {
            string result = server2.GetSendAddFromMerId(1, 9999, merid, "", 1);
            return Content(result);
        }

        //新的全部送餐范围接口
        public ActionResult GetAllAddByUser()
        {
            string result = server2.GetAllAddByUser("", 1);
            return Content(result);

        }

        #region 获取用户信息
        public ActionResult MyInfor()
        {
            Model.View_User userinfoModel = (Model.View_User)Session[SessionStorage.UserLogin];//将Session保存的实体转成可直接使用的实体
            //var data=new
            return Json(userinfoModel);
        }
        #endregion

        #region 获取联系人地址信息
        public ActionResult getAddress()
        {
            try
            {
                Model.View_User userinfoModel = (Model.View_User)Session[SessionStorage.UserLogin];//将Session保存的实体转成可直接使用的实体
                int acc = int.Parse(userinfoModel.AccID.ToString());
                string result = server1.GetUser_Contact(acc, GetYZM._YZM, 1);
                Model.DataResult dr = ParseClass<Model.DataResult>.StrDeserialize(result, 1);
                //tal = dr.total.ToString();
                List<Model.User_Contact_T> ls = new List<Model.User_Contact_T>();
                JObject jb = JObject.Parse(result);
                IList<JToken> jieguo = jb["rows"].Children().ToList();
                ls = ParseClass<Model.User_Contact_T>.JsonList(jieguo);

                //List<Model.User_Contact_T> ls = new GetContactInfo().getAllContact(userinfoModel, out t);
                var data = new
                {
                    total = ls.Count,
                    rows = ls
                };
                return Json(data);
            }
            catch (Exception) { return null; }
        }

        //新的获取地址列表接口
        public ActionResult GetUserSendAddr(string MerId)
        {
            string openid = Session[SessionStorage.OpenID].ToString();
            string result = server2.GetUserSendAddr(openid, MerId, "", 1);
            return Content(result);
        }

        public ActionResult addNewAddress(Model.User_Contact_T userC)
        {
            try
            {

                Model.View_User userinfoModel = (Model.View_User)Session[SessionStorage.UserLogin];//将Session保存的实体转成可直接使用的实体
                if (userC.MerAddId != 0)
                {
                    userC.AccID = int.Parse(userinfoModel.AccID.ToString()); //用户id
                    userC.ContactState = 1;
                    string json = userC.ToJson();
                    string result = server1.UpDateUser_Contact(json, 1, GetYZM._YZM, 1);//更新用户联系人
                    JObject jb = JObject.Parse(result);
                    if (jb["BS"].ToString() == "1")
                    {
                        return Content(jb["BS"].ToString());
                    }
                    else
                    {
                        return Content(jb["Msg"].ToString());
                    }
                }
                else
                {
                    return Content("请选择派送范围");
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

        public ActionResult updateAddress(Model.User_Contact_T userC)
        {
            try
            {
                Model.View_User userinfoModel = (Model.View_User)Session[SessionStorage.UserLogin];//将Session保存的实体转成可直接使用的实体
                userC.AccID = int.Parse(userinfoModel.AccID.ToString()); //用户id
                userC.ContactState = 1;
                string json = userC.ToJson();
                string result = server1.UpDateUser_Contact(json, 2, GetYZM._YZM, 1);//更新用户联系人
                JObject jb = JObject.Parse(result);
                if (jb["BS"].ToString() == "1")
                {
                    return Content(jb["BS"].ToString());
                }
                else
                {
                    return Content(jb["Msg"].ToString());
                }
            }
            catch (Exception) { return null; }
        }

        public ActionResult delAddress(Model.User_Contact_T userC)
        {
            try
            {
                int contactid = userC.ID;
                int[] intArray = new int[1];

                intArray[0] = userC.ID;
                string result = server1.User_ContactDelByID(intArray, GetYZM._YZM, 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();
                if (bs == "1")
                {
                    return Content("OK");
                }
                else
                {
                    return Content(searcho["Msg"].ToString());
                }
            }
            catch (Exception) { }
            return null;
        }

        //新的地址增删改
        public ActionResult SetUserSendAddr(string json, int tag)
        {
            json = json.Replace("\\\"", "");
            string result = server2.SetUserSendAddr(json, tag, "", 1);
            return Content(result);

        }
        #endregion

        #region 根据商户id获取该商户所有派送范围
        /// <summary>
        /// 根据商户id获取该商户所有派送范围
        /// </summary>
        /// <returns></returns>
        public ActionResult getallsendfrommerid()
        {
            try
            {
                orderinfo oinfo = (orderinfo)Session[SessionStorage.OrderInfo];//将Session保存的实体转成可直接使用的实体
                string merid = oinfo.ShopInfo.MerID;
                Model.View_User userinfoModel = (Model.View_User)Session[SessionStorage.UserLogin];//将Session保存的实体转成可直接使用的实体
                int accid = int.Parse(userinfoModel.AccID.ToString());
                string address = server2.GetUserContactByMerid(merid, accid, GetYZM._YZM, 1);
                //string address = server2.GetSendAddFromMerId(1,1000,merid,GetYZM._YZM, 1);
                List<Model.User_Contact_T> ls = new List<Model.User_Contact_T>();
                JObject jb = JObject.Parse(address);
                IList<JToken> jieguo = jb["rows"].Children().ToList();
                ls = ParseClass<Model.User_Contact_T>.JsonList(jieguo);
                var data = new
                {
                    list = ls
                };
                return Json(data);
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        #endregion

        #region 根据范围获取商户
        /// <summary>
        /// 根据范围获取商户
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public ActionResult getmerfromadd(User_Contact_T t)
        {
            try
            {
                //int aa=int.Parse(vom.MerAddId);
                string result = server2.GetMerAddFromId(1, 1000, t.MerAddId, GetYZM._YZM, 1);
                Model.DataResult dr = ParseClass<Model.DataResult>.StrDeserialize(result, 1);
                List<Model.View_Order_MerSend> ls = new List<Model.View_Order_MerSend>();
                JObject jb = JObject.Parse(result);
                IList<JToken> jieguo = jb["rows"].Children().ToList();
                ls = ParseClass<Model.View_Order_MerSend>.JsonList(jieguo);
                var data = new
                {
                    total = ls.Count,
                    rows = ls
                };
                return Json(data);
            }
            catch (Exception) { return null; }
        }
        #endregion

        #region 获取钱包余额
        public ActionResult getWaltBalance()
        {
            try
            {
                //获取当前登录用户的用户ID
                Model.View_User userinfoModel = (Model.View_User)Session[SessionStorage.UserLogin];//将Session保存的实体转成可直接使用的实体
                int acc = int.Parse(userinfoModel.AccID.ToString());
                string result = server2.GetUserWalt(acc, GetYZM._YZM, 1);//请求接口数据
                JObject jb = JObject.Parse(result);//将接口返回的结果序列化
                string bs = jb["BS"].ToString();//获取结果成功与否的标识
                if (bs == "1")
                {
                    IList<JToken> jt = jb["rows"].Children().ToList();//解析返回的结果
                    List<View_Order_UserWalt> uw = new List<View_Order_UserWalt>();//声明实体类
                    //List<View_Order_UserWalt> uw_New = new List<View_Order_UserWalt>();//声明实体类
                    uw = ParseClass<View_Order_UserWalt>.JsonList(jt);
                    //if (uw.Count > 0)
                    //{
                    //    foreach (View_Order_UserWalt item in uw)
                    //    {
                    //        if (item.AccID == acc)
                    //        {
                    //            uw_New.Add(item);
                    //        }
                    //    }
                    //}
                    var data = new
                    {
                        total = uw.Count,
                        rows = uw
                    };
                    return Json(data, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return null;

                }
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

        #region 获取用户钱包流水
        public ActionResult getWaltWater(string AccNum, string WaltID, int pageIndex, int pageSize)
        {
            try
            {
                string result = server2.GetOrder_FlowMon(pageIndex, pageSize, AccNum.Trim(), WaltID, "", "", "", GetYZM._YZM, 1);
                JObject jb = JObject.Parse(result);
                string bs = jb["BS"].ToString();
                if (bs == "1")
                {
                    List<View_FlowMon_New> ls = new List<View_FlowMon_New>();
                    IList<JToken> list = jb["rows"].Children().ToList();
                    ls = ParseClass<View_FlowMon_New>.JsonList(list);
                    foreach (View_FlowMon_New item in ls)
                    {
                        item.WaltFlowTime = DateTimeHelper.ToDate2(item.WaltFlowTime);
                        item.WaltEndNub = Math.Round(item.WaltEndNub * 0.01, 2);
                        item.WaltHaveNub = Math.Round(item.WaltHaveNub * 0.01, 2);
                        item.WaltNowNub = Math.Round(item.WaltNowNub * 0.01, 2);
                        //string WaltEndNub = Convert.ToDouble(item.WaltEndNub).ToString("0.00");
                        //string WaltHaveNub = Convert.ToDouble(item.WaltHaveNub).ToString("0.00"); 
                    }
                    var json = new
                    {
                        total = jb["total"].ToString(),
                        rows = ls
                    };
                    return Json(json);
                }
                else
                {
                    //return null;
                    return Content(jb["Msg"].ToString());
                }
            }
            catch (Exception ex)
            {
                return Content(ex.ToString());
            }
        }
        #endregion

        #region 获取用户积分
        public ActionResult getUserInt()
        {
            //获取当前登录用户的用户ID
            Model.View_User userinfoModel = (Model.View_User)Session[SessionStorage.UserLogin];//将Session保存的实体转成可直接使用的实体
            int acc = int.Parse(userinfoModel.AccID.ToString());

            string result = server2.GetOrder_UserInt_T(1, 10, userinfoModel.AccID, GetYZM._YZM, 1);
            JObject jb = JObject.Parse(result);
            List<Model.View_Order_UserInt> ls = new List<View_Order_UserInt>();
            if (jb["BS"].ToString() == "1")
            {
                IList<JToken> jt = jb["rows"].Children().ToList();
                ls = ParseClass<View_Order_UserInt>.JsonList(jt);
            }
            var json = new
            {
                total = jb["total"].ToString(),
                rows = ls
            };
            return Json(json, JsonRequestBehavior.AllowGet);
        }
        #endregion

        public class View_FlowMon_New
        {
            public string AccCall { get; set; }
            public string AccCerNub { get; set; }
            public string AccCerType { get; set; }
            public string AccCerType_DicName_Login { get; set; }
            public int AccID { get; set; }
            public string AccIdentifier { get; set; }
            public string AccName { get; set; }
            public string AccNum { get; set; }
            public int? AccSex { get; set; }
            public string CategoryID { get; set; }
            public string CategoryID_DicName_SystemIdentity { get; set; }
            public string DepID { get; set; }
            public string DepID_DepName_Department { get; set; }
            public string FlowMonID { get; set; }
            public string IdentityID { get; set; }
            public string IdentityID_DiName_SystemIdentity { get; set; }
            public string OperNum { get; set; }
            public int? OrdrID { get; set; }
            public string PayID { get; set; }
            public string SataeID { get; set; }
            public string StateID_DicName_SystemIdentity { get; set; }
            public string WaltBZ { get; set; }
            public double WaltEndNub { get; set; }
            public int WaltFlowOper { get; set; }
            public string WaltFlowTime { get; set; }
            public string WaltFlowType { get; set; }
            public string WaltFlowTypeName { get; set; }
            public double WaltHaveNub { get; set; }
            public string WaltID { get; set; }
            public string WaltName { get; set; }
            public double WaltNowNub { get; set; }
        }

        #region 商城信息
        /// <summary>
        /// 商城信息类型
        /// </summary>
        /// <param name="Type"></param>
        /// <param name="YZM"></param>
        /// <param name="RETID"></param>
        /// <returns></returns>
        public ActionResult Get_Order_InformationByType(string Type, string YZM, int RETID)
        {
            try
            {
                string result = server2.Get_Order_InformationByType(Type, YZM, RETID);
                return Content(result);
            }
            catch (Exception) { return null; }
        }

        /// <summary>
        /// 商城信息详情
        /// </summary>
        /// <param name="InformationID"></param>
        /// <param name="YZM"></param>
        /// <param name="RETID"></param>
        /// <returns></returns>
        public ActionResult Details_Order_Information(string InformationID, string YZM, int RETID)
        {
            try
            {
                string result = server2.Details_Order_Information(InformationID, YZM, RETID);
                return Content(result);
            }
            catch (Exception) { return null; }
        }
        #endregion

        #region 地址区域
        /// <summary>
        /// 获取启用的二级地址区域
        /// </summary>
        /// <returns></returns>
        public ActionResult Get_User_DistrictsTwoByDistrictID(string DistrictID)
        {
            try
            {
                string result = server2.Get_User_DistrictsTwoByDistrictID(DistrictID);
                return Content(result);
            }
            catch (Exception) { return null; }
        }

        /// <summary>
        /// 获取启用的三级地址区域
        /// </summary>
        /// <param name="DistrictID"></param>
        /// <returns></returns>
        public ActionResult Get_User_DistrictsThreeByDistrictID(string DistrictID)
        {
            try
            {
                string result = server2.Get_User_DistrictsThreeByDistrictID(DistrictID);
                return Content(result);
            }
            catch (Exception) { return null; }
        }

        /// <summary>
        /// 更新用户的配送地址
        /// </summary>
        /// <param name="json">更新信息</param>
        /// <param name="tag">操作标签（1：新增；2：修改；3：删除）</param>
        /// <returns></returns>
        public ActionResult UpdateUserSendAddr(int Tag, Order_UserSendAddr UserSendAddr)
        {
            try
            {
                string result = "";
                View_User userinfoModel = (View_User)Session[SessionStorage.UserLogin];
                if (userinfoModel != null)
                {
                    UserSendAddr.AccID = userinfoModel.AccID;
                }
                string userJson = JsonConvert.SerializeObject(Session[SessionStorage.OpenID]).ToString();
                if (userJson != "")
                {
                    UserSendAddr.OpenId = userJson.Replace("\"", "");
                }
                #region 转换传入的信息
                Order_UserSendAddr New_District = new Order_UserSendAddr
                {
                    ID = UserSendAddr.ID,
                    AccID = UserSendAddr.AccID,
                    Name = UserSendAddr.Name,
                    ContactDistrict = UserSendAddr.ContactDistrict,
                    AddrContent = UserSendAddr.AddrContent,
                    TelNum = UserSendAddr.TelNum,
                    OpenId = UserSendAddr.OpenId,
                    DistrictID = UserSendAddr.DistrictID
                };
                #endregion
                string a = New_District.ToJson();
                result = server2.SetUserSendAddr(New_District.ToJson(), Tag, GetYZM._YZM, 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();
                if (bs == "1")
                {
                    return Content(bs);
                }
                else
                {
                    return Content(searcho["Msg"].ToString());
                }
            }
            catch (Exception ex)
            {
                return Content("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// 获取用户已经添加的地址
        /// </summary>
        /// <param name="OpenId">微信ID</param>
        /// <param name="AccID">用户ID</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式（1：JSON；2：XML）</param>
        /// <returns></returns>
        public ActionResult GetAllUserSendAddr(string OpenId, int AccID, string YZM, int RETID)
        {
            try
            {
                string userJson = JsonConvert.SerializeObject(Session[SessionStorage.OpenID]).ToString();
                if (userJson != "")
                {
                    OpenId = userJson.Replace("\"", "");
                }
                string result = server2.GetAllUserSendAddr(OpenId, AccID, YZM, RETID);
                return Content(result);
            }
            catch (Exception) { return null; }
        }
        
        #endregion

    }
}
